package com.qu.Media;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.qu.Media.media.ImageGalleryActivity;
import com.qu.Media.media.SelectImageActivity;
import com.qu.Media.media.bean.TestImage;
import com.qu.Media.media.config.SelectOptions;
import com.qu.Media.media.util.CollectionUtil;
import com.qu.Media.media.util.DialogHelper;
import com.qu.Media.media.widget.TweetPicturesLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
    private CircleImageView avator;
    private Boolean mIsUploadIcon;
    private File mCacheFile;
    private String testImagePath;
    private TweetPicturesLayout picturesLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        avator = (CircleImageView) findViewById(R.id.mCircleImageView);
        avator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAvatarOperation();
            }
        });
        picturesLayout = (TweetPicturesLayout) findViewById(R.id.fl_picture);
    }
    //测试从本地或相机来选择图片
    public void test(View v){
        //启动选择图片的Ativity
        SelectImageActivity.show(this, new SelectOptions.Builder()
                .setHasCam(true)
                .setSelectCount(9)
            //    .setSelectedImages(mImageAdapter.getPaths()) //设置所选择的图片
                .setCallback(new SelectOptions.Callback() {
                    @Override
                    public void doSelected(String[] images) { //回调所选择的图片
                        //选择的图片
                        testPictureLayout(images);
                    }
                }).build());
    }
    //测试自定义图片的布局
    public void testPicture(View v){
        if(testimages != null&& testimages.size()>0) {
            TestImage[] images = CollectionUtil.toArray(testimages,TestImage.class);
            picturesLayout.setImage(images);
        }
    }
    private List<TestImage> testimages = new ArrayList<>();
    private void testPictureLayout(String[] images) {
         for(int i=0;i<images.length;i++){
             TestImage img = new TestImage();
             img.setW(0);
             img.setW(0);
             img.setHref(images[i]);
             img.setThumb(images[i]);
             testimages.add(img);
         }
    }

    //查看或更换头像
    private void showAvatarOperation() {
        DialogHelper.getSelectDialog(this,
                "请选择操作",
                getResources().getStringArray(R.array.avatar_option), "取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i) {
                            case 0:
                                SelectImageActivity.show(MainActivity.this, new SelectOptions.Builder()
                                        .setSelectCount(1)
                                        .setHasCam(true)
                                        .setCrop(700, 700)
                                        .setCallback(new SelectOptions.Callback() {
                                            @Override
                                            public void doSelected(String[] images) {
                                                String path = images[0];
                                                testImagePath = path;
                                                uploadNewPhoto(new File(path),path);
                                            }
                                        }).build());
                                break;

                            case 1:
                                //正确的方式是先去上传头像，头像上传成功后，在去跟新头像，然后在册除
                                //缓存的文件。现在是测试我们直接把路径更新上去.
                                if(testImagePath != null) {
                                    showUserAvatar(MainActivity.this, testImagePath);
                                }else{
                                    Toast.makeText(MainActivity.this,"图像不存在，跟新失败...",
                                            Toast.LENGTH_SHORT).show();
                                }
                                break;
                        }
                    }


                }).show();
    }
    //上传头像
    private void uploadNewPhoto(File file,String path) {
        // 获取头像缩略图
        if (file == null || !file.exists() || file.length() == 0) {
            Toast.makeText(this,"图像不存在，上传文件失败...",Toast.LENGTH_SHORT).show();
        } else {
            mIsUploadIcon = true;
            this.mCacheFile = file;
            //TODO 上传的API
            //这里测试
            Glide.with(this).load(path).into(avator);
        }
    }

    /**
     * 显示用户头像大图
     *
     * @param context
     * @param avatarUrl
     */
    public void showUserAvatar(Context context, String avatarUrl) {
        if (TextUtils.isEmpty(avatarUrl)) {
            return;
        }
        ImageGalleryActivity.show(context, avatarUrl);
    }
    //册除缓存文件
    public void deleteCacheFile(){
        if(mCacheFile != null && mCacheFile.exists()){
            mCacheFile.delete();
        }
    }
    /**
     * take photo
     */
    private void startTakePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,
                REQUEST_CODE_GETIMAGE_BYCAMERA);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        try {
            startTakePhoto();
        } catch (Exception e) {
            Toast.makeText(this, "相机无法完成初始化，请正确授权...", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(this, "相机无法完成初始化，请正确授权...", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions
            , @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    public void testGit(){
        Toast.makeText(this,"测试",Toast.LENGTH_SHORT).show();
    }
}
